﻿CREATE PROCEDURE [acms].[Topic_Put]
	@Id int, 
	@SiteId int,
	@Name varchar(100),
	@Sequence int,
	@ConcurencyId rowversion,
	@IdOut int output,
	@SequenceOut int output,
	@ConcurencyIdOut rowversion output
AS
	if @Sequence is null or @Sequence < 0 begin
		select @Sequence = IsNull(Max(Sequence) + 1, 0) from Topic_View where SiteId = @SiteId
	end
	
	if exists (Select null from Topic_View where Id = @Id) begin
		update Topics
		set
			SiteId = @SiteId,
			Name = @Name,
			Sequence = @Sequence
		where	
			Id = @Id
			and ConcurencyId = @ConcurencyId
			
		if @@RowCount = 0
			return -100
		else
			set @IdOut = @Id
	end
	else if @Id is not null and @Id <> 0 begin
		return -200
	end
	else begin
		insert into Topics
			(SiteId, Name, Sequence)
		values
			(@SiteId, @Name, @Sequence)
			
		set @IdOut = @@Identity
	end
	
	set @SequenceOut = @Sequence
	select @ConcurencyId = ConcurencyId From Topic_View Where Id = @IdOut
	
	RETURN 0;